package jun.comm.netkit;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class JunProtocol {

	private static ExecutorService executorService = Executors.newFixedThreadPool(10);
	private ByteBuffer buffer = ByteBuffer.allocate(1024);
	public String cont = "";

	public JunProtocol() {
	}

	public JunProtocol(int bufferSize) {
		this.buffer = ByteBuffer.allocate(bufferSize);
	}
	
	// 设置数据
	public String setCont(String cont){
		this.cont = cont;
		return this.cont;
	}

	// 处理连接请求
	public void accept(SelectionKey key) throws IOException {

		// 创建socket通道
		SocketChannel sktChan = ((ServerSocketChannel) key.channel()).accept();

		// 设置为非阻塞模式
		sktChan.configureBlocking(false);

		// 将选择器绑定到socket通道， 并且设置为读取模式
		sktChan.register(key.selector(), SelectionKey.OP_READ, buffer);

		System.out.println("接收到客户端的连接:" + sktChan.getLocalAddress());
		
	}

	// 处理读取
	public void read(SelectionKey key) throws Exception {
		//取消读事件的监控
        key.cancel();
        //获得线程并执行
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                	// 获得与客户端通信的信道
                	SocketChannel readChannel = (SocketChannel) key.channel();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int read = 0;
					while ((read = readChannel.read(buffer)) > 0) {
	                    // 没有获取到数据，退出
        				if (read == -1) {
        					readChannel.close();
        					System.out.println("关闭通道");
        					break;
        				}

        				if (read != -1) {
        					 buffer.flip();
                             while (buffer.hasRemaining()) {
                                 baos.write(buffer.get());
                             }
        				}
        				buffer.clear();
                    }
                    System.out.println("服务器端接收到的数据："+ new String(baos.toByteArray()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
	}
	
	// 处理写入
	public void write(SelectionKey key) throws Exception {
		write(key, "");
	}
	
	// 处理写入
	public void write(SelectionKey key, String str) throws Exception {
		//取消读事件的监控
        key.cancel();
        
        
        //拿到线程并执行
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                	// 获得与客户端通信的信道
                	SocketChannel writeChannel = (SocketChannel) key.channel();
                	
                	// 准备发送的文本
        			String sendString = cont;
        			if(!str.isEmpty()){
        				sendString = str;
        			}
                    
        			// 设置数据
                    buffer.put(sendString.getBytes());
                    buffer.flip();
                    // 写入数据
                    writeChannel.write(buffer);
                    
                    // 关闭输出流
                    writeChannel.shutdownOutput();
                    
                } catch (Exception e) {
                    e.printStackTrace();
                }       
            }
        });
	}
}
